<template>
    <section class="content">
        <Panel :expandable="false" :expand="true">
            <template slot="title">
                预审查询
            </template>
            <template slot="body">
                <el-form ref="form" :model="this" label-width="100px" :rules="rules">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="店铺收款账号">
                                <el-select v-model="receiverNumber" class="full-cell">
                                    <el-option v-for="r in shopList" :label="r" :key="r" :value="r"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="订单日期">
                                <el-date-picker
                                    v-model="orderDate"
                                    :type="datetimeType"
                                    :value-format="datetimeValueFormat"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    class="full-cell"
                                    >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="订单金额" prop="orderAmount">
                                <el-input v-model="orderAmount"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" style="padding-left: 12px">
                            <el-button type="success" @click="handleSearch">搜索</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </template>
        </Panel>

        <Panel :expandable="false" :expand="true">
            <template slot="title">订单总金额：{{totalAmount}}</template>
            <template slot="body">
                <el-form label-width="70px">
                    <el-row :gutter="12">
                        <el-col :span="7">
                            <el-form-item label="订单编号">
                                <el-input v-model="orderNumber" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-button type="success" @click="handleSearchByOrderNumber">搜索</el-button>
                            <el-button type="primary" :disabled="buttondisabled" @click="handleCommit">提款申请</el-button>
                        </el-col>
                    </el-row>
                </el-form>
                <el-table :data="subList" header-row-class-name="header-class">
                    <el-table-column align="center" prop="orderCreated" label="订单日期"></el-table-column>
                    <el-table-column align="center" label="订单编号">
                        <template slot-scope="scope">
                            <span :style="{'color': scope.row.isInResult?'red':''}">{{scope.row.orderId}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="total" label="订单金额"></el-table-column>
                    <el-table-column align="center" prop="currency" label="货币单位"></el-table-column>
                    <el-table-column align="center" prop="statusStr" label="预审状态"></el-table-column>
                    <el-table-column align="center" label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" icon="iconfont rticon-shanchu" @click="handleDelete(scope.row)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="clear-fix">
                    <el-pagination
                        style="float: right; margin-top: 20px;"
                        background
                        layout="total, prev, pager, next"
                        @current-change="handleCurrentChange"
                        @prev-click="handlePrev"
                        @next-click="handleNext"
                        :page-size="searchParam.rows"
                        :current-page="searchParam.page"
                        :total="searchParam.total">
                    </el-pagination>
                </div>
            </template>
        </Panel>

        <el-dialog append-to-body :visible.sync="visible">
            <el-form ref="form2" :model="this" :rules="rules2" label-width="100px">
                <el-form-item label="申请名称：">
                    <el-input v-model="applyName" style="width: 217px"></el-input>
                </el-form-item>
                <el-form-item label="付款类型：">
                    <el-select v-model="type">
                        <el-option v-for="t in types" :label="t.label" :value="t.value" :key="t.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-row v-if="type===1">
                    <el-col style="width: 100px">
                        <el-form-item label="付款比例："></el-form-item>
                    </el-col>
                    <el-col :span="4" class="c">
                        <el-form-item label="" prop="ratio1">
                            <el-input v-model.number="ratio1">
                                <template slot="append">%</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" class="c">
                        <el-form-item label="" prop="ratio2">
                            <el-input v-model.number="ratio2">
                                <template slot="append">%</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" class="c">
                        <el-form-item label="" prop="ratio3">
                            <el-input v-model.number="ratio3">
                                <template slot="append">%</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="type===2">
                    <el-col style="width: 100px">
                        <el-form-item label="付款金额："></el-form-item>
                    </el-col>
                    <el-col :span="4" class="c">
                        <el-form-item label="" prop="amount1">
                            <el-input v-model.number="amount1">
                                <template slot="append">{{currencyUnit}}</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" class="c">
                        <el-form-item label="" prop="amount2">
                            <el-input v-model.number="amount2">
                                <template slot="append">{{currencyUnit}}</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" class="c">
                        <el-form-item label="" prop="amount3">
                            <el-input v-model.number="amount3">
                                <template slot="append">{{currencyUnit}}</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleSave">保存</el-button>
                <el-button @click="visible = false">关闭</el-button>
            </div>
        </el-dialog>
    </section>
</template>
<script>
import Panel from '@/components/common/panel'
import instance from '@/api/index.js'
import apiUrls from '@/js/common/apiUrls'
import {floatAdd, datetimeType, datetimeValueFormat} from '@/js/util'

export default {
    name: "paymentAudit",
    data() {
        return {
            begin: '',
            end: '',
            datetimeType: datetimeType,
            datetimeValueFormat: datetimeValueFormat,
            visible: false,
            receiverNumber: "",
            orderDate: "",
            orderAmount: "",
            list: [],
            subList: [],
            // totalAmount: "",
            orderNumber: "",
            type: "",
            types: [{
                value: 1,
                label: "比例"
            },{
                value: 2,
                label: "金额"
            }],
            ratio1: "",
            ratio2: "",
            ratio3: "",
            amount1: "",
            amount2: "",
            amount3: "",
            receivers: [],
            shopList: [],
            applyName: this.getCurrentDateStr(),

            searchParam: {
                page: 1,
                rows: 10,
                total: 0
            },

            rules:{
                orderAmount: [{
                    required: true, message: '请输入订单金额', trigger: 'blur'
                }]
            },

            headerRowStyle: {
                'background-color': 'red'
            },
            // rules2: {
            //     ratio1: [{type: 'number', message: "请输入数值类型", trigger: 'blur'}],
            //     ratio2: [{type: 'number', message: "请输入数值类型", trigger: 'blur'}],
            //     ratio3: [{type: 'number', message: "请输入数值类型", trigger: 'blur'}],

            //     amount1: [{type: 'number', message: "请输入数值类型", trigger: 'blur'}],
            //     amount2: [{type: 'number', message: "请输入数值类型", trigger: 'blur'}],
            //     amount3: [{type: 'number', message: "请输入数值类型", trigger: 'blur'}]
            // }
          buttondisabled: true,
        };
    },
    components: {
        Panel
    },
    methods: {
        padding(n) {
            if(n < 10) {
                return "0" + n;
            } else {
                return "" + n;
            }
        },
        getDateStr(date) {
            if(date) {
                return date.getFullYear() + "-" + this.padding(date.getMonth()+1) + "-" + this.padding(date.getDate());
            }
        },
        getCurrentDateStr() {
            let now = new Date();
            return now.getFullYear() + this.padding(now.getMonth()+1) + this.padding(now.getDate()) + this.padding(now.getHours()) + this.padding(now.getMinutes());
        },
        handleSearch() {
            this.$refs.form.validate((valid)=>{
                if(valid) {
                    let self = this;
                    let param = Object.assign({
                        account: this.receiverNumber,
                        total: this.orderAmount || null,
                        // begin: this.getDateStr(this.orderDate[0]),
                        // end: this.getDateStr(this.orderDate[1]),
                        begin: this.orderDate[0],
                        end: this.orderDate[1]
                    });
                    this.begin = param.begin;
                    this.end = param.end;

                    instance({
                        method: 'post',
                        url: apiUrls.receive.paymentOrderList,
                        params: param
                    }).then(function (data) {
                        if(data.data.success){
                            let statuses = ['未命中', '疑似命中', '异常'];
                            self.list = data.data.data.map(function(item) {
                                item.statusStr = statuses[item.status] || '';
                                return item;
                            });
                            self.handleSearchByOrderNumber();
                            self.deletedList = [];
                          self.buttondisabled = self.list.length> 0? false: true;
                        }
                    }).catch(function (err) {
                        console.log(err)
                    })
                }
            });
        },

        handleSearchByOrderNumber() {
            this.searchParam.page =  1;
            let result = this.searchInList(this.orderNumber, this.searchParam.page);
            this.subList = result.list;
            this.searchParam.total = result.total;
        },

        searchInList(orderNumber, pageIndex) {
            console.log("orderId: ", orderNumber, ", page: ", pageIndex);
            let tempList = [];
            this.list.forEach(function(item) {
                item.isInResult = false;
            });
            if(orderNumber == undefined || orderNumber == '') {
                tempList = this.list.slice();
            } else {
                tempList = this.list.filter((o)=>{
                    return o.orderId.toLowerCase().indexOf(orderNumber.toLowerCase()) > -1;
                });
                tempList.forEach(function(item) {
                    item.isInResult = true;
                });
                console.log("before: ", tempList);
                tempList = tempList.concat(this.list.filter((o)=>{
                    return o.orderId.toLowerCase().indexOf(orderNumber.toLowerCase()) === -1;
                }));
                console.log("after: ", tempList);
            }

            let pageSize = this.searchParam.rows;
            let total = tempList.length;
            let subList = tempList.slice((pageIndex - 1) * pageSize, pageIndex * pageSize);
            console.log("sl: ", subList);
            return {
                total: total,
                list: subList
            };

        },

        handleDelete(item) {
            for(let i = 0; i < this.list.length; i++) {
                if(this.list[i].orderId === item.orderId) {
                    this.list.splice(i, 1);
                }
            }

            for(let i = 0; i < this.subList.length; i++) {
                if(this.subList[i].orderId === item.orderId) {
                    this.subList.splice(i, 1);
                }
            }

            this.deletedList.push(item.orderId);

            if(this.searchParam.total - 1 <= (this.searchParam.page - 1) * this.searchParam.rows) {
                this.handleCurrentChange(this.searchParam.page - 1);
            } else {
                this.handleCurrentChange(this.searchParam.page);
            }
        },

        handleCurrentChange(pageIndex) {
            this.searchParam.page = pageIndex;
            let result = this.searchInList(this.orderNumber, this.searchParam.page);
            this.subList = result.list;
            this.searchParam.total = result.total;
        },

        handleNext(pageIndex) {
            this.searchParam.page = pageIndex;
            let result = this.searchInList(this.orderNumber, this.searchParam.page);
            this.subList = result.list;
            this.searchParam.total = result.total;
        },

        handlePrev(pageIndex) {
            this.searchParam.page = pageIndex;
            let result = this.searchInList(this.orderNumber, this.searchParam.page);
            this.subList = result.list;
            this.searchParam.total = result.total;
        },

        isNumericValidator(rule, value, callback) {

            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.ruleForm2.pass) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        },
        // 提交审核
        handleCommit() {
            this.visible = true;
        },

        handleSave() {
            let self = this;

            // 校验
            this.$refs.form2.validate().then((valid)=>{
                if(valid) {
                    // 如果是百分比需要是100%
                    if(this.type === 1) {
                        if(this.ratio1 + this.ratio2 + this.ratio3 != 100) {
                            this.$message.error("比例和必须是100%");
                            return;
                        }
                    }

                    let param = {
                        account: this.receiverNumber,
                        total: this.orderAmount,
                        begin: this.begin,
                        end: this.end,
                        applyName: this.applyName,
                        paymentType: this.type,
                        paymentRatio: (this.type == 1 ? [this.ratio1, this.ratio2, this.ratio3] : [this.amount1, this.amount2, this.amount3]).join('|'),
                        deleteOrders: this.deletedList.join(',')
                    };
                    instance({
                        method: 'post',
                        url: apiUrls.receive.paymentCommit,
                        data: param,
                        hideError: true,
                    }).then(function (data) {
                        if(data.data.success){
                            self.$emit('commited', data.data.msg);
                        } else {
                            self.$alert(data.data.msg || '操作失败！', '提示', {
                                confirmButtonText: '确定',
                                callback: action => {

                                }
                            });
                        }
                    }).catch(function (err) {
                        // console.log(err)
                        self.$alert(err, '提示', {
                            confirmButtonText: '确定',
                            callback: action => {

                            }
                        });
                    });
                } else {
                    //self.$message.error("");
                }
            });

        },
        getShopList() {
            let self = this;
            let param = {
                    id: "0"
            };
            instance({
                method: 'post',
                url: apiUrls.receive.shopList,
                data: param
            }).then(function (data) {
                self.shopList = data.data.data || [];
                if(data && data.data && data.data.data && data.data.data.length > 0) {
                    let shops = {};
                    data.data.data.forEach(function(s) {
                        let accounts = s.accounts;
                        accounts && accounts.forEach(function(a) {
                            shops[a] = a;
                        });
                    });
                    let arrShops = [];
                    for(let s in shops) {
                        arrShops.push(s);
                    }
                    self.shopList = arrShops;
                    self.receiverNumber = arrShops[0];
                    //self.handleSearch();
                } else {
                    self.$error("授权店铺列表为空");
                }
            }).catch(function (err) {
                console.log(err)
            });
        }
    },

    created() {
        //this.handleSearch();
        this.getShopList();
    },

    computed: {
        currencyUnit() {
            let item = this.list[0];

            return item && item.currency || "";
        },

        canCommit() {
            return this.list && this.list.length > 0;
        },

        rules2() {
            if(this.type === 2) {
                return {
                    amount1: [{type: 'number', message: "请输入数值类型", trigger: 'blur'}],
                    amount2: [{type: 'number', message: "请输入数值类型", trigger: 'blur'}],
                    amount3: [{type: 'number', message: "请输入数值类型", trigger: 'blur'}]
                };
            } else {
                return {
                    ratio1: [{type: 'number', message: "请输入数值类型", trigger: 'blur'}],
                    ratio2: [{type: 'number', message: "请输入数值类型", trigger: 'blur'}],
                    ratio3: [{type: 'number', message: "请输入数值类型", trigger: 'blur'}]
                };
            }
        },
        totalAmount() {
            if(this.list && this.list.length) {
                let total = floatAdd(this.list.map((item)=>{
                    return item.total;
                }));

                return total;
            }

            return '';
        }
    },

    watch: {
        type() {
            debugger;
            if(this.$refs.form2) {
                setTimeout(()=>{
                    this.$refs.form2.clearValidate()
                }, 500);
            }
        }
    }
}
</script>
<style scoped>
.el-date-editor {
    width: 100%!important;
}

.el-range-separator {
    width: 22px!important;
}

</style>
<style>

.c .el-form-item__content {
    margin-left: 0!important;
}
</style>
